<template>
  <div>
    <div class="table-operator">
      <a-button v-action:add type="primary" icon="check-circle" @click="validate" :loading="confirmLoading">保存</a-button>
      <a-button v-action:add icon="rollback" @click="handleGoBack">返回</a-button>
    </div>
    <a-form @submit="handleSubmit" :form="form" class="form">
    <a-card class="card" title="优惠券基本信息">
        <a-row class="form-row" :gutter="96">
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="券名称">
              <a-input v-decorator="['name', {rules: [{ required: true, message: '必输', whitespace: true}]} ]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="原价">
              <a-input v-decorator="['costPrice', {rules: [{ required: true, message: '必输', whitespace: true}]} ]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="现价">
              <a-input v-decorator="['price', {rules: [{ required: true, message: '必输', whitespace: true}]} ]"/>
            </a-form-item>
          </a-col>
<!--          <a-col :lg="8" :md="12" :sm="24">-->
<!--            <a-form-item label="营业时间">-->
<!--              <a-range-picker style="width: 100%" :disabled="isDisabled" v-decorator="[ 'validTime', {rules: [{ type: 'array', required: true, message: '必选!' }]}]"/>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
          <!--<a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="批次类型">
              <a-select :disabled="isDisabled" v-decorator="[ 'stockType', {rules: [{required: true, message: '必输'}, ],initialValue:'merNORMAL'} ]" >
                <a-select-option value="merNORMAL">固定面额满减券</a-select-option>
                <a-select-option value="DISCOUNT">折扣券</a-select-option>
                <a-select-option value="EXCHANGE">换购券</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>-->
        </a-row>
        <a-row class="form-row" :gutter="96">
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="券面额" extra="兑换券=0,折扣券=折数,例如：兑换券输入0,折扣券八折输入0.8">
              <a-input v-decorator="['amount', {rules: [{ required: true, message: '必输', whitespace: true}]} ]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="数量">
              <a-input v-decorator="['stockNum', {rules: [{ required: true, message: '必输', whitespace: true}]} ]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="商户id">
              <a-input v-decorator="['merchantId', {rules: [{ required: true, message: '必输', whitespace: true}]} ]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="96">
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="使用须知">
              <a-input v-decorator="['description', {rules: [{ required: true, message: '必输', whitespace: true}]} ]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="类型">
              <a-radio-group @change="onchange" buttonStyle="solid" v-decorator="[ 'type', {rules: [{ required: true, message: '请选择' }], initialValue: 1}]">
                <!--<a-radio-button :value="1">免费优惠券</a-radio-button>-->
                <a-radio-button :value="1">兑换券</a-radio-button>
                <a-radio-button :value="2">折扣券</a-radio-button>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="96">
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="主图" extra="主图推荐500*500">
              <a-upload
                listType="picture-card"
                class="avatar-uploader"
                :showUploadList="false"
                :action="baseUrl + '/system/common/uploadFile'"
                :beforeUpload="beforeUpload"
                @change="uploadChange"
              >
                <img v-if="imageUrl" :src="imageUrl" alt="avatar" width="300px"/>
                <div v-else>
                  <a-icon :type="confirmLoading ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">Upload</div>
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
        </a-row>

    </a-card>

    </a-form>
  </div>
</template>

<script>
  import moment from 'moment';
  import pick from 'lodash.pick'
  import { saveOrUpdate } from '@/api/system/coupon'
  /**
   * 数据
   */
  const data = function() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 }
      },
      id: null,
      loading: false,
      visible: false,
      confirmLoading: false,
      isDisabled: false,
      editProps: [],
      imageUrl: '',
      fileName: null,
      baseUrl: process.env.VUE_APP_API_BASE_URL,
      isValue: true,
      form: this.$form.createForm(this)
    }
  }
  const created = function() {
    // storeList().then(res => {
    //   if (res.code === 200) {
    //     this.editProps = res.data
    //   }
    // })
    this.$nextTick(() => {
      this.loadEditInfo(this.record)
    })
  }

  export default {
    props: {
      record: {
        type: [Object, String],
        default: ''
      }
    },

    data: data,
    created: created,
    /**
     * 方法
     */
    methods: {
      handler ({BMap, map}) {
        map.centerAndZoom(new BMap.Point(this.model.lng,this.model.lat), 15);
        // 初始化地图,设置中心点坐标
        var point = new BMap.Point(119.8025089500, 25.4890556400)
        map.centerAndZoom(point, 13)

        // 添加鼠标滚动缩放
        map.enableScrollWheelZoom();
        // 添加缩略图控件
        map.addControl(new BMap.OverviewMapControl({isOpen:false,anchor:BMAP_ANCHOR_BOTTOM_RIGHT}));
        // 添加缩放平移控件
        map.addControl(new BMap.NavigationControl());
        //添加比例尺控件
        map.addControl(new BMap.ScaleControl());
        //添加地图类型控件
        //map.addControl(new BMap.MapTypeControl());

        //设置标注的图标
        var icon = new BMap.Icon("./static/img/map.png",new BMap.Size(100,100));
        //设置标注的经纬度
        var marker = new BMap.Marker(new BMap.Point(121.160724,31.173277),{icon:icon});
        //把标注添加到地图上
        map.addOverlay(marker);
        var content = "<table>";
        content = content + "<tr><td> 编号：001</td></tr>";
        content = content + "<tr><td> 地点：上海汉得信息技术股份有限公司</td></tr>";
        content = content + "<tr><td> 时间：2018-1-3</td></tr>";
        content += "</table>";
        var infowindow = new BMap.InfoWindow(content);
        // 图标点击的时候显示标注
        marker.addEventListener("click",function(){
          this.openInfoWindow(infowindow);
        });
        // 标注默认显示
        // var infoWindow = new BMap.InfoWindow(content) // 创建信息窗口对象
        // map.openInfoWindow(infoWindow, point)
      },
      getClickInfo (e) {
        console.log(e.point.lng)
        console.log(e.point.lat)
        this.center.lng = e.point.lng
        this.center.lat = e.point.lat
        this.lng=e.point.lng
        this.lat=e.point.lat
      },
      handleGoBack () {
        this.$emit('onGoBack')
      },
      handleSubmit (e) {
        e.preventDefault()
      },
      validate () {
        const { form: { validateFields } } = this
        this.confirmLoading = true
        validateFields((errors, values) => {
          if (!errors) {
            values.id = this.id
            values.fileUrl = this.imageUrl
            //values.businessHours = values['validTime'][0].format('MM-DD') +' '+ values['validTime'][1].format('MM-DD')
            console.log(values)
            saveOrUpdate(values).then((res) => {
              this.confirmLoading = false
              if (res.code === 200) {
                this.handleGoBack()
              }
            })
          } else {
            this.confirmLoading = false
          }
        })
      },
      loadEditInfo (record) {
        if (!record) {
          return
        }
        this.id = record.id
        this.isDisabled = true
        this.imageUrl = record.fileUrl
        if (record.type === 5) {
          this.isValue = false
        }
        let validTime = []
        validTime.push(moment(record.availableBeginTime))
        validTime.push(moment(record.availableEndTime))
        record.validTime = validTime
        const { form } = this
        const formData = pick(record, ['integralRate','thresholdPrice','isBargain','bargainCount','bargainAmount','storeId','productName','goodsName','costPrice', 'stockName', 'stockType', 'couponAmount', 'transactionMinimum', 'validTime', 'maxAmount', 'isShare',
          'maxCoupons', 'maxCouponsPerUser', 'sortNo', 'amount', 'amount2','goodsCode','kanAmount','kanCount', 'description', 'isRefund', 'onedayQuota', 'templateMsg'])
        form.setFieldsValue(formData)
      },
      filterOption (input, option) {
        return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      },
      uploadChange(info) {
        if (info.file.status === 'uploading') {
          this.confirmLoading = true;
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          this.imageUrl = info.file.response.fileUrl;
          this.filename = info.file.response.filename
          this.confirmLoading = false;
        }
      },
      beforeUpload(file) {
        return true;
      },
      onchange(e){
        if(e.target.value == 5){
          this.isValue = false;
        }else{
          this.isValue = true;
        }
      },
    }
  }
</script>

<style lang="less" scoped>
  .bm-view{
    width: 100%;
    height: 100%;
    margin-top: 20px;
  }
  .mylabel{
    margin-right: 20px;
  }

  .card {
    margin-bottom: 24px;
  }

  .popover-wrapper {
    /deep/ .antd-pro-pages-forms-style-errorPopover .ant-popover-inner-content {
      min-width: 256px;
      max-height: 290px;
      padding: 0;
      overflow: auto;
    }
  }

  .antd-pro-pages-forms-style-errorIcon {
    user-select: none;
    margin-right: 24px;
    color: #f5222d;
    cursor: pointer;

    i {
      margin-right: 4px;
    }
  }

  .antd-pro-pages-forms-style-errorListItem {
    padding: 8px 16px;
    list-style: none;
    border-bottom: 1px solid #e8e8e8;
    cursor: pointer;
    transition: all .3s;

    &:hover {
      background: #e6f7ff;
    }

    .antd-pro-pages-forms-style-errorIcon {
      float: left;
      margin-top: 4px;
      margin-right: 12px;
      padding-bottom: 22px;
      color: #f5222d;
    }

    .antd-pro-pages-forms-style-errorField {
      margin-top: 2px;
      color: rgba(0, 0, 0, .45);
      font-size: 12px;
    }
  }
</style>
